//
//  SafeDetailDangerViewController.m
//  Estate
//
//  Created by wangdongdong on 2017/10/25.
//  Copyright © 2017年 ttsx. All rights reserved.
//

#import "SafeDangerModel.h"
#import "SafeDangerCell.h"

#import "SafeDetailDangerViewController.h"

@interface SafeDetailDangerViewController ()<UITableViewDelegate, UITableViewDataSource>

// 表格
@property (strong, nonatomic) TPKeyboardAvoidingTableView *tableView;

// 数据源
@property (strong, nonatomic) NSMutableArray *dataArr;

@end


@implementation SafeDetailDangerViewController

// 数据源
- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (TPKeyboardAvoidingTableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[TPKeyboardAvoidingTableView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT - 188) style:UITableViewStylePlain];
        _tableView.backgroundColor = UIColorFromRGB(0xf2f2f2);
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.bounces = NO;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [_tableView registerNib:[UINib nibWithNibName:@"SafeDangerCell" bundle:nil] forCellReuseIdentifier:@"dangerCell"];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
    [self.view addSubview:self.tableView];
    [self getCheckinformation];
}

// 添加通知 (暂存/提交检查信息)
- (void)viewWillAppear:(BOOL)animated {
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveSupervisionSafetyInspection:) name:@"updateSafeCheck" object:nil];
}

// 移除通知 (暂存/提交检查信息)
- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"updateSafeCheck" object:nil];
}

#pragma MARK - 查找检查信息, 刷新表格
- (void)getCheckinformation {
    [self.dataArr removeAllObjects];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM SAFE_DANGER WHERE BASIC_RECORD_ID = '%@' ORDER BY CHECK_TYPE ASC", self.safeModel.id];
    FMResultSet *results = [db executeQuery:sqlStr];
    while ([results next]) {
        SafeDangerModel *model = [[SafeDangerModel alloc] init];
        
        model.id = [results stringForColumn:@"ID"];
        model.proId = [results stringForColumn:@"PRO_ID"];
        model.basicId = [results stringForColumn:@"BASIC_RECORD_ID"];
        model.recordUser = [results stringForColumn:@"RECORD_USER"];
        model.recordType = [results stringForColumn:@"RECORD_TYPE"];
        model.recordTitle = [results stringForColumn:@"RECORD_TITLE"];
        model.recordNumber = [results stringForColumn:@"RECORD_NUMBER"];
        model.checkTypeName = [results stringForColumn:@"CHECK_NAME"];
        model.checkType = [results stringForColumn:@"CHECK_TYPE"];
        model.checkCase = [results stringForColumn:@"CHECK_INFO"];
        model.supervisionEvaluation = [results stringForColumn:@"IS_ON_POSITION"];
        model.extendInfo = [results stringForColumn:@"EXTEND_INFO"];
        model.createusername = [results stringForColumn:@"CREATE_USER_NAME"];
        model.createtime = [results stringForColumn:@"CREATE_TIME"];
        model.createip = [results stringForColumn:@"CREATE_IP"];
        model.modifyusername = [results stringForColumn:@"MODIFY_USER_NAME"];
        model.modifytime = [results stringForColumn:@"MODIFY_TIME"];
        model.modifyip = [results stringForColumn:@"MODIFY_IP"];
        
        [self.dataArr addObject:model];
    }
    [db close];
    // 刷新视图
    [self.tableView reloadData];
}

#pragma MARK - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 190;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    // 数据
    SafeDangerModel *model = self.dataArr[section];
    
    SafeDangerCell *dangerCell = [tableView dequeueReusableCellWithIdentifier:@"dangerCell" forIndexPath:indexPath];
    dangerCell.selectionStyle = UITableViewCellSelectionStyleNone;
    // 是否可编辑
    if ([self.safeModel.state isEqualToString:@"1"] || self.isDiary) {
        [dangerCell isNoEdit];
    }
    // 检查类型名称
    dangerCell.nameLabel.text = model.checkTypeName;
    
    // 检查情况
    if (model.checkCase && ![model.checkCase isEqualToString:@""]) {
        dangerCell.describeText.text = model.checkCase;
    }
    dangerCell.checkSituationBlock = ^(NSString *str) {
        model.checkCase = str;
    };
    
    // 监理评价(是否符合要求)
    if (model.supervisionEvaluation && ![model.supervisionEvaluation isEqualToString:@""]) {
        if ([model.supervisionEvaluation isEqualToString:@"1"]) {
            dangerCell.conformSwitch.on = YES;
            
        } else {
            dangerCell.conformSwitch.on = NO;
        }
    }
    dangerCell.supervisionEvaluationBlock = ^(NSString *str) {
        model.supervisionEvaluation = str;
    };
    return dangerCell;
}

#pragma mark - 提交保存危险性较大工程监理检查
- (void)saveSupervisionSafetyInspection:(NSNotification *)notification {
    // 接收通知来的信息
    NSDictionary *parameDic = [notification object];
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    for (SafeDangerModel *model in self.dataArr) {
        // 字段及对应值
        NSDictionary *pragameDic = [NSDictionary dictionary];
        pragameDic = @{
                       @"ID":DEFISNUL(model.id),
                       @"PRO_ID":DEF_PERSISTENT_GET_OBJECT(@"proid"),
                       @"BASIC_RECORD_ID":DEFISNUL(parameDic[@"safeBaseID"]),
                       @"RECORD_USER":DEFISNUL(DEF_PERSISTENT_GET_OBJECT(@"userid")),
                       @"RECORD_TYPE":DEFISNUL(@"SAFE_RECORD_03"),
                       @"RECORD_TITLE":DEFISNUL(parameDic[@"title"]),
                       @"RECORD_NUMBER":DEFISNUL(parameDic[@"recordNumber"]),
                       @"CHECK_NAME":DEFISNUL(model.checkTypeName),
                       @"CHECK_TYPE":DEFISNUL(model.checkType),
                       @"CHECK_INFO":DEFISNUL(model.checkCase),
                       @"IS_ON_POSITION":DEFISNUL(model.supervisionEvaluation),
                       @"EXTEND_INFO":@"",
                       @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"loginuser"),
                       @"CREATE_TIME":DEFISNUL([LSUtility nowTime]),
                       @"CREATE_IP":DEFISNUL([LSUtility getIPAddress]),
                       @"MODIFY_USER_NAME":@"",
                       @"MODIFY_TIME":@"",
                       @"MODIFY_IP":@"",
                       @"LOCAL_MODIFY_USER_NAME":@"",
                       @"LOCAL_MODIFY_TIME":@"",
                       @"LOCAL_MODIFY_STATE":@"ADD",
                       };
        
        BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:SAFE_DANGER];
        if (isAdd) {
            NSLog(@"更新危险性较大工程监理检查成功");
            
        } else {
            NSLog(@"更新危险性较大工程监理检查失败");
        }
    }
    
    // 刷新安全列表页
    [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshSafeList" object:nil];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

